/*************************************************************************
	> File Name: sign.c
	> Author: Potter
	> Mail: tobewhatwewant@gmail.com
	> Created Time: 2014年05月28日 星期三 22时16分15秒
 ************************************************************************/

#include<stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <wait.h>
#include <signal.h>

void parent_stop();
void child_stop();

int main(int argc, char * argv[]) {
    pid_t pid1, pid2;

    while((pid1 = fork()) == -1)
        perror("fork1");

    if(pid1 > 0) {
        while((pid2 = fork()) == -1)
            perror("fork2");

        if(pid2 > 0) {
            signal(SIGINT, parent_stop);
            signal(SIGQUIT, parent_stop);
            fprintf(stdout, "This is parent process, pid %d\n", getpid());
            sleep(5);
            kill(pid1, SIGUSR1);
            kill(pid2, SIGUSR2);
            waitpid(pid1, 0, 0);
            waitpid(pid2, 0, 0);
            fprintf(stdout, "Parent process (pid=%d) finisted!\n", getpid());
        } else {
            fprintf(stdout, "This is child process 2, pid = %d !\n", getpid()); 
            signal(SIGUSR2, child_stop);
            sleep(6);
        }

    } else {
        fprintf(stdout, "This is child process 1, pid = %d !\n", getpid());
        signal(SIGUSR2, child_stop);
        sleep(6);
    }
    
    return 0;
}

void parent_stop() {
    fprintf(stdout, "This is parent_stop pid=%d!\n", getpid()); 
}

void child_stop() {
    fprintf(stdout, "This is child_stop pid=%d!\n", getpid()); 
}
